<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>弹幕聊天室</title>
<style>
	body{
        width: 100%;
        margin: 0 auto 0;
    }
    #main{
        width: 640px;
        margin: 0 auto 0;
        position: relative;
        text-align: center;
    }
    #video-body{
        background-color: #111;
        overflow: hidden;
        position: relative;
        z-index: 1;
        margin: 0 auto 0;
    }
    .active{
        white-space :nowrap;
        position: absolute;
        display: inline-block;
        animation: barrage 5s linear;
        animation-fill-mode: forwards;
        color: white;
        /*-webkit-animation:barrage 5s linear 0 1 normal forwards;
        -moz-animation:barrage 5s linear 0 1 normal forwards;
        -o-animation: barrage 5s linear 0 1 normal forwards;*/
        z-index: 5;
    }
    .tools {
    	padding:2px 0;
    }
    .tools input{
		width:76%;
		font-size:14px;
		padding:6px;
    }
    .tools button{
    	width:20%;
    	padding:6px;
    }
 	.info{
 		text-align: center;
 		margin-top:20px;
 		font-size:12px;
 	}
    @keyframes barrage{
        0%{
            left:100%;
        }
        100%{
            left: -100%;
        }
    }	

    .chatroom {
    	width:640px;
    	height:120px;
    	overflow:hidden;
    	margin:1em auto;
    	position:relative;
    	background:#fff;
    	border:1px solid #ccc;
    }
    .chatroom h2{
    	font-size:14px;
    	margin:0;
    	padding:5px;
    	background:#fff;
    	position:relative;
    }
    .chatroom ol {
    	position:absolute;
    	bottom:0;
    	left:-10px;
    	width:100%;
    	height:80px;
    	overflow:auto;
    	font-size:12px;
    }
    .question, .question-dialog{
    	background-color: #111;
    	opacity: 0.8;
    	filter: alpha(opacity=0.8);
	    box-sizing: border-box;
	    padding: 0 0 3px 5px;
	    margin-top: -16px;
	    color: #FFF;
	    position: absolute;
	    bottom: 42px;
	    z-index: 1;
	    width: inherit;    
    }

    .question-dialog{
       height: 110px;
       z-index: 11;
    }
    
    .question-title{
		text-align: left;
		margin: 6px 0px;
		padding-bottom: 15px;
    }
	.question-item{
		display: inline-block;
	    width: 100px;
	    background: #909090;
	    border-radius: 13px;
	    margin-bottom: 10px;
	}
	.question a{
		text-decoration: none;
		color: #FFF;
	    height: 100%;
	    width: 100%;
	    display: inline-block;
	}
	.question-countdown{
		float: right;
		margin-right: 10px;
	}
	
	.question-bingo, .question-wrong{
		background-color: #FFF;
	}
	.question-bingo{
		color: green;
	}
	.question-wrong{
		color: red;
	}
</style>
</head>
<body>
	<div class="info">
		使用其他账号发送聊天室消息：<a href="https://rongcloud.github.io/websdk-demo/api-test.html">https://rongcloud.github.io/websdk-demo/api-test.html</a>
	</div>

	<div id="main">
		<div id="video-body">
			<video id="video" height="480" width="640" loop="true" autoplay>
				<source id="vi"  src="../res/heal-the-world.mp4" type="video/mp4" />
				Your browser does not support the video tag.
			</video>
		</div>
		
		<div class="question-dialog" style="display: none;">
			本轮结束
		</div>

		<div id="tools" class="tools">
			<input type="text" id="message" value="请输入消息">
			<button id="send" type="button">发送</button>
		</div>
	</div>

	<!-- <div class="chatroom" id="chatroom007">
		<h2>聊天室 007 <em></em> （测试两个聊天室消息是否会串）</h2>
		<ol></ol>
	</div> -->
	
</body>

<script src="../lib/jquery-3.1.1.js"></script>
<script src="../lib/vue-2.1.4.js"></script>
<script src="//cdn.ronghub.com/RongIMLib-2.5.4.js"></script>
<script type="text/javascript" src="./chatroom.js"></script>


<script type="text/javascript">
$("#tools").hide();

/*
默认 1个用户 不能同时加入两个聊天室，需要通过工单申请客服开通
*/
var appInfo = {
	"appKey" : "8w7jv4qb78a9y",
	"token" : "ZThhLI1Xa1BX5EMREAdArWSH6ouuI8NT/fNmMkzF+4IOKIoFvbsi6JnH8QmnSltLkCcsK8vOgKl3IZgfbxFiWg=="
};

//列表聊天室 id= chatRoomId-007
/*
(function(){
	// return false;

	var chatRoomInfo = {
		"chatRoomId" : "chatRoomId-007",
		"count" : 20
	};

	RongChatRoom.init(appInfo, chatRoomInfo, {
		onSuccess: function(chatRoom) {
			// 加入聊天室成功。
			showNewMessage("加入聊天室成功");

			//聊天室发消息
			var content = "这是一条发给 chatroom 007 的消息。"
			chatRoom.sendMessage(content, {
		        onSuccess: function (message) {
					showNewMessage(content);
		        },
		        onError: function (errorCode,message) {
		            console.log("发送聊天室消息失败", errorCode);
		        }
		    });
		},
		onError: function(error) {
			alert('加入聊天室失败。')
			// 加入聊天室失败
		},
		onMessage : function(message){
			// console.log("007");
			// console.log(message);
			showNewMessage("chatroomId: " + message.targetId + ",  messageUId: " + message.messageUId);
		}
	});

	function showNewMessage(content){
		$("#chatroom007 ol").append("<li>" + content + "</li>");
	}
})();
*/

var utils = {
	templateRender: function(template, data) {
	    template = template || "";
	    data = data || [""];
	    var re = /{%((?:(?!%}).)+)%}/g, reExp = /(^( )?(var|if|for|else|switch|case|default|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
	    var add = function(line, js) {
	        js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
	            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
	        return add;
	    }
	    var match;
	    while(match = re.exec(template)) {
	        add(template.slice(cursor, match.index))(match[1], true);
	        cursor = match.index + match[0].length;
	    }
	    add(template.substr(cursor, template.length - cursor));
	    code += 'return r.join("");';
	    data = isNaN(data.length) ? [data] : data;
	    var html = "";
	    for(var i = 0, length = data.length; i < length; i++) {
	        html += new Function(code.replace(/[\r\t\n]/g, '')).apply(data[i]);
	    }
	    return html;    
	}
};

function registerMessage(type,propertys){
	var messageName = type; // 消息名称。
	var objectName = "s:" + type; // 消息内置名称，请按照此格式命名 *:* 。
	var mesasgeTag = new RongIMLib.MessageTag(true,true); //true true 保存且计数，false false 不保存不计数。

	RongIMClient.registerMessageType(messageName,objectName,mesasgeTag,propertys);
}

//弹幕聊天室 id= chatRoomId-008

(function(){
	var chatRoomInfo = {
		"chatRoomId" : "chatRoomId-008",
		"count" : 20
	};

	RongChatRoom.init(appInfo, chatRoomInfo, {
		onSuccess: function(chatRoom) {
			//注册自定义消息
			var propertys = ["title","submitAPI","questions"]; // 消息类中的属性名。
			registerMessage("QA",propertys);

			// 加入聊天室成功。
			console.log("加入聊天室成功");
			console.log(chatRoom);
			$("#message").val('加入聊天室成功，当前用户：' + chatRoom.currentUser.userId);

			//调用示例
			apiDemo(chatRoom);
		},
		onError: function(error) {
			alert('加入聊天室失败。')
			// 加入聊天室失败
		},
		onMessage : function(message){
			if(message.objectName == "s:QA" && !message.offLineMessage){
				qaLive(message.content)
			}
			updateDanmu(message.content.content);
		}
	});
})();

var qaTpl = [
	'<div class="question">',
		'<div class="question-countdown">',
			'倒计时: <span id="countdown">10</span>s',
		'</div>',
		'<dl>',
			'<dt class="question-title">',
				'{% this.question %}',
				'{% for(var i=0; i < this.answers.length; i++){ %}',
					'<dd class="question-item" id="answer-{% this.answers[i].id %}">',
						'<a href="#" onclick=submitAnswer({%this.answers[i].id%},"{%this.submitAPI%}","{%this.answers[i].bingo%}")>{% this.answers[i].answer %}</a>',
					'</dd>',
				'{% } %}',
			'</dt>',
		'</dl>',
	'</div>',
].join('');

var qaDialog = $('.question-dialog');
function QAdialogOperator(isHide){
	var type = 'block';
	if (isHide) {
		type = 'none';
	}
	qaDialog.css('display', type);
}

var interval = 0;

function startCount(){
	interval = setInterval(function(){
		var counter = $('#countdown');
		var count = counter.html();
		if (count > 0) {
			 counter.html(count - 1);
		}else{
			stopCount();
			QAdialogOperator();
		}
	}, 1000);
}

function stopCount(){
	clearInterval(interval);
}

function submitAnswer(id, submitAPI, bingo){
	console.log(submitAPI);
	
	stopCount();

	var isBingo = false;
	if (id == bingo) {
		isBingo = true;
	}
	// todo: post ajax submitAPI
	var tpl = '#answer-{%this.id%}';
	id = utils.templateRender(tpl, {
		id: id
	});

	
	var node = $(id);
	var siblings = node.siblings();
	siblings.find('a').css('pointerEvents', 'none');

	if (isBingo) {
		node.addClass('question-bingo');
		node.html('正确');
	}

	if (!isBingo) {
		node.addClass('question-wrong');
		node.html('答错了');
	}
	
}

function qaLive(content){
	console.log(content)

	stopCount();
	var questions = JSON.parse(content.questions);
	// 暂时处理单个问答
	var question = questions[0];
	question.submitAPI = content.submitAPI;
	var qaNode = utils.templateRender(qaTpl, question);

	$('.question').remove();

	var main = $('#main');
	$('#main').append(qaNode);
	QAdialogOperator(true);
	startCount();
}

/*
发送消息按钮，点击发送将push input框消息到服务器端，并清空input框。
此处targetId为聊天室Id，勿和用户id混淆。
*/
function apiDemo(chatRoom){
	$("#tools").show();
	//点击发送消息
	$("#send").click(function(){
		var content = $("#message").val();
			content = '<div style="color:red;background:#333;padding:5px;">' + content + '</div>';
		chatRoom.sendMessage({"content" : content}, {
	        onSuccess: function (message) {
	            console.log("发送聊天室消息成功");
	            updateDanmu(content);
	        },
	        onError: function (errorCode,message) {
	            console.log("发送聊天室消息失败",errorCode);
	        }
	    });
	});

	//循环发消息
	var sends = setInterval(function(){
		var content = {
			content: getRandomText()
		};

		//聊天室发消息
		chatRoom.sendMessage(content, {
	        onSuccess: function (message) {
				updateDanmu(chatRoom.id + ": " + message.content.content);
	        },
	        onError: function (errorCode,message) {
	            console.log("发送聊天室消息失败", errorCode);
	        }
	    });
    },2000);
	
	//聊天室信息
	chatRoom.getInfo({
			order : RongIMLib.GetChatRoomType.REVERSE, // 排序方式。
			memberCount : 10 // 0 - 20
		},{
		onSuccess : function(chatRoomInfo){
			console.log("获取聊天室信息成功");
			console.log(chatRoomInfo);
		},
		onError : function(error){

		}
	});

    //聊天室退出
    /*
    chatRoom.quit({
		onSuccess : function(){
			console.log("退出成功")
		},
		onError : function(error){
			console.log("退出失败", error)
		}
	});
	*/
}

/*
发送弹幕方法
*/
function updateDanmu(message){
	//弹幕高度随机
	var margintop = Math.random()*160 + Math.random()*160;
		margintop = Math.ceil(margintop);
	$("#video-body").append("<div class='active' style='top:"+margintop+"px;'>"+message+"</div>");
}

function getRandomText(){
	var messages = "琵琶行，白居易，浔阳江头夜送客，枫叶荻花秋瑟瑟。主人下马客在船，举酒欲饮无管弦。醉不成欢惨将别，别时茫茫江浸月。忽闻水上琵琶声，主人忘归客不发。寻声暗问弹者谁？琵琶声停欲语迟。移船相近邀相见，添酒回灯重开宴。千呼万唤始出来，犹抱琵琶半遮面。转轴拨弦三两声，未成曲调先有情。弦弦掩抑声声思，似诉平生不得志。低眉信手续续弹，说尽心中无限事。轻拢慢捻抹复挑，初为霓裳后六幺。大弦嘈嘈如急雨，小弦切切如私语。嘈嘈切切错杂弹，大珠小珠落玉盘。间关莺语花底滑，幽咽泉流冰下难。冰泉冷涩弦凝绝，凝绝不通声渐歇。别有幽愁暗恨生，此时无声胜有声。银瓶乍破水浆迸，铁骑突出刀枪鸣。曲终收拨当心画，四弦一声如裂帛。东船西舫悄无言，惟见江心秋月白。沉吟放拨插弦中，整顿衣裳起敛容。自言本是京城女，家在虾蟆陵下住。十三学得琵琶成，名属教坊第一部。曲罢曾教善才服，妆成每被秋娘妒。武陵年少争缠头，一曲红绡不知数。钿头银篦击节碎，血色罗裙翻酒污。今年欢笑复明年，秋月春风等闲度。弟走从军阿姨死，暮去朝来颜色故。门前冷落车马稀，老大嫁作商人妇。商人重利轻别离，前月浮梁买茶去。去来江口求空船，绕船月明江水寒。夜深忽梦少年事，梦啼红妆泪阑干。我闻琵琶已叹息，又闻此语重唧唧。同是天涯沦落人，相逢何必曾相识。我从去岁辞帝京，谪居卧病浔阳城。浔阳地僻无音乐，终岁不闻丝竹声。住近湓城地低湿，黄芦苦竹绕宅生。其间旦暮闻何物？杜鹃啼血猿哀鸣。春江花朝秋月夜，往往取酒还独倾。岂无山歌与村笛？呕哑嘲哳难为听。今夜闻君琵琶语，如听仙乐耳暂明。莫辞更坐弹一曲，为君翻作琵琶行。感我此言良久立，却坐促弦弦转急。凄凄不似向前声，满座重闻皆掩泣。座中泣下谁最多？江州司马青衫湿";

	//将字符串拆分成数组
	// messages = messages.split("。");
	messages = messages.split(/，|。|？/);

	var len = messages.length;
	var index = Math.ceil(Math.random()*1000000)%len;

	// console.log(messages[index]);
	return messages[index];
}
</script>

</html>